package com.yuma.springshiroredisthymeleaf.handler;


import com.yuma.springshiroredisthymeleaf.common.ResultEnum;
import com.yuma.springshiroredisthymeleaf.common.ResultInfo;
import com.yuma.springshiroredisthymeleaf.exception.GoodsException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


// 全局异常处理  @ControllerAdvice/@RestControllerAdvice + @ExceptionHandler
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = GoodsException.class)
    @ResponseBody
    public ResultInfo goodsExceptionHandler(HttpServletRequest req, GoodsException e){
        logger.error("发生业务异常！原因是：{}",e.getMsg());
        return ResultInfo.error(e.getCode(),e.getMsg());
    }

    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultInfo npeExceptionHandler(HttpServletRequest req, NullPointerException e){
        logger.error("发生空指针异常！原因是:",e.getMessage());
        return ResultInfo.error(ResultEnum.BODY_NOT_MATCH.getMsg());
    }

    @ExceptionHandler(value = AuthorizationException.class)
    public ModelAndView exceptionHandler(HttpServletRequest req, AuthorizationException e){
        ModelAndView modelAndView = new ModelAndView("unauthorized");
        return modelAndView;
    }

    @ExceptionHandler(value = AuthenticationException.class)
    public ModelAndView exceptionHandler(HttpServletRequest req, AuthenticationException e){
        ModelAndView modelAndView = new ModelAndView("login");
        return modelAndView;
    }
}